package com.example.kotlin.ui.dialog;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;


/**
 * @author chenmengjia
 */
public abstract class BaseDialogFragment extends DialogFragment implements View.OnTouchListener {
    public View mContentView;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //去除默认title
        if (getDialog() != null) {
            getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        //点击外部不消失
//        getDialog().setCanceledOnTouchOutside(getCanceledOnTouchOutside());

        mContentView = inflater.inflate(initContentView(), container, false);
        return mContentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        boolean isShow = this.getShowsDialog();
        this.setShowsDialog(false);
        super.onActivityCreated(savedInstanceState);
        this.setShowsDialog(isShow);
        View view = getView();
        if (view != null) {
            if (view.getParent() != null) {
//                throw new IllegalStateException("DialogFragment can not be attached to a container view");
            }
            if (this.getDialog() != null) {
                this.getDialog().setContentView(view);
            }
        }
        final Activity activity = getActivity();
        if (activity != null && this.getDialog() != null) {
            this.getDialog().setOwnerActivity(activity);
        }
        this.getDialog().setCancelable(false);
        this.getDialog().getWindow().getDecorView().setOnTouchListener(this);
        this.getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE) {
                    dismiss();
                    return true;
                }
                return false;
            }
        });
        if (savedInstanceState != null) {
            Bundle dialogState = savedInstanceState.getBundle("android:savedDialogState");
            if (dialogState != null) {
                this.getDialog().onRestoreInstanceState(dialogState);
            }
        }


        Window window = getDialog().getWindow();
        if (getAnimations() != -1) {
            //给dialog设置进出动画
            window.setWindowAnimations(getAnimations());
        }
        //设置背景透明
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();
        params.gravity = getGravity();
        params.width = getDialogWidth();
        params.height = getDialogHeight();
        if (!getInterceptOnTouchOutside()){
            //不拦截对话框外touch事件
            params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        }
        window.setAttributes(params);
        window.setLayout(getDialogWidth(), getDialogHeight());
        initView();
        initListener();
        initData();
    }

    @Override
    public void show(@NonNull FragmentManager manager, @Nullable String tag) {
        try {
            //在每个add事务前增加一个remove事务，防止连续的add
            manager.beginTransaction().remove(this).commit();
            super.show(manager, tag);
        } catch (Exception e) {
           // Logger.e(BaseDialogFragment.class, "show error : " + e);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (getCanceledOnTouchOutside() && getDialog().isShowing()) {
            dismiss();
            return true;
        }
        return false;
    }

    protected abstract int initContentView();

    protected abstract void initView();

    protected abstract void initListener();

    protected abstract void initData();

    /**
     * 设置点击外部对话框是否消失
     *
     * @return false:默认不消失
     */
    protected boolean getCanceledOnTouchOutside() {
        return false;
    }

    /**
     * 设置是否拦截对话框外touch事件
     *
     * @return true:默认拦截，touch事件不往下传递
     */
    protected boolean getInterceptOnTouchOutside() {
        return true;
    }

    /**
     * 获取dialog位置
     *
     * @return Gravity.CENTER:默认居中
     */
    protected int getGravity() {
        return Gravity.CENTER;
    }

    protected int getDialogWidth() {
        return WindowManager.LayoutParams.WRAP_CONTENT;
    }

    protected int getDialogHeight() {
        return WindowManager.LayoutParams.WRAP_CONTENT;
    }

    /**
     * 获取dialog进出动画
     *
     * @return
     */
    protected int getAnimations() {
        return -1;
    }

    protected void removeKeyListener() {
        this.getDialog().setOnKeyListener(null);
    }
}
